import json
from contextlib import closing
from genericpath import exists
from os import makedirs

import requests


def download(photo_url, dir_name, filename):
    if not exists(dir_name):
        makedirs(dir_name)
    print(filename + ": " + photo_url)
    jpg_filename = dir_name + '/' + filename
    if not exists(jpg_filename):
        with closing(requests.get(url=photo_url, stream=True, timeout=90)) as r:
            with open(jpg_filename, 'ab+') as f:
                for chunk in r.iter_content(chunk_size=1024):
                    if chunk:
                        f.write(chunk)
                        f.flush()
                f.close()


if __name__ == '__main__':
    with open('json/paster.json') as f_obj:
         tem = json.load(f_obj)
         data = tem['data']
         for i in data:
             dirName = i['category']['name']
             items = i['items']
             for j in items:
                 img = j['img']
                 imgName = j['name'] + ".jpg"
                 download(img, dirName, imgName)